package com.flycent.hqhs.ui;


import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.BrandRecommend;
import com.flycent.hqhs.bean.MainTopAdvertisement;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.bean.Product;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsScrollGridView;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.CountdownClock;
import com.flycent.hqhs.ui.view.CountdownClock.ClockListener;
import com.flycent.hqhs.ui.view.MyPagerGalleryView;
import com.flycent.hqhs.ui.view.MyPagerGalleryView.MyOnItemClickListener;
import com.flycent.hqhs.ui.view.ScrollViewRefreshProxy;
import com.flycent.hqhs.ui.view.ScrollViewRefreshProxy.OnRefreshActionListener;
import com.flycent.hqhs.util.ContextUtil;
import com.flycent.hqhs.util.NetworkUtil;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 首页
 * @author fbl
 */
@SuppressLint("HandlerLeak") 
public class MainActivity extends BaseActivity implements OnRefreshActionListener{ 

	@ViewInject(id = R.id.right_icon , click = "butClick") ImageView mRightImg;
	@ViewInject(id = R.id.main_search_edit, click = "butClick") EditText mSearchEdit;
	@ViewInject(id = R.id.main_attention_lin, click = "butClick") LinearLayout mAttentionLin;
	@ViewInject(id = R.id.main_panorama_lin, click = "butClick") LinearLayout mPanoramaLin;
	@ViewInject(id = R.id.main_group_lin, click = "butClick") LinearLayout mGroupLin;
	@ViewInject(id = R.id.main_recommend_lin, click = "butClick") LinearLayout mRecommendLin;//品牌推荐
	@ViewInject(id = R.id.time_limit_lin, click = "butClick") LinearLayout mTimeLimitLin;
	@ViewInject(id = R.id.brand_group_lin, click = "butClick") LinearLayout mBrandGroupLin;
//	@ViewInject(id = R.id.main_viewflow_lin, click = "butClick") LinearLayout mViewFlowLin; //删除了viewFlow模式
	
	/** 顶部branner 滚动广告 */
	@ViewInject(id = R.id.main_branner_lin) LinearLayout mMainPageLin; //滚动garllery
	@ViewInject(id = R.id.main_branner_grally) MyPagerGalleryView mMainPageGalleryView; //滚动garllery
	@ViewInject(id = R.id.main_branner_butttom_lin) LinearLayout mMainPageGalleryLin; //底部圆点容器

	@ViewInject(id = R.id.main_scroll) ScrollView mScrollView;
	/** 限时特卖的三张图片 */
	@ViewInject(id = R.id.time_limit_image1) ImageView mTimeLimitImg1; 
	@ViewInject(id = R.id.time_limit_image2) ImageView mTimeLimitImg2; 
	@ViewInject(id = R.id.time_limit_image3) ImageView mTimeLimitImg3; 
	/** 团购三张图片 */
	@ViewInject(id = R.id.main_group_img1) ImageView mGroupImg1; 
	@ViewInject(id = R.id.main_group_img2) ImageView mGroupImg2; 
	@ViewInject(id = R.id.main_group_img3) ImageView mGroupImg3; 
	/**  */
	@ViewInject(id = R.id.main_brand_gridView) AbsScrollGridView mBrandGridView;
	@ViewInject(id = R.id.main_product_recommend_grid) AbsScrollGridView mProductRecommendGrid;
	/** 9个品牌推荐viewpage */
	@ViewInject(id = R.id.main_brand_recommend_viewpager) ViewPager mViewPage;
	@ViewInject(id = R.id.ovalLayout1) LinearLayout mOvalLayout; // 圆点容器 
	@ViewInject(id = R.id.main_brand_viewpageLin) LinearLayout mMainViewpageLin; //viewpage的父layout

	private MainTopAdvertisement mTopAdvertisement;
	private List<MainTopAdvertisement.AdServing> mAdServings;
	private PageEntity<Product> msEntity;
	private List<Product> mSpecialSales ;
	private List<BrandRecommend> mBrandRecommends;
	private List<Product> mRecommend;
	private List<Product> mGroupRecommend;
	//	private MainBrandGridAdapter mBrandRecommendAdapter;
	private MainProductRecommendAdapter mProductRecommendAdapter;
	private static final String TAG = "MainActivity"; 

	/** 9个品牌推荐的view视图 */
	private View view;
	private List<View> viewList;// view数组
	private int curIndex = 0;
	private int oldIndex = 0;

	PullToRefreshScrollView mPtrScrollView;
	ScrollViewRefreshProxy mScrollViewRefreshProxy;

	private Handler mHandler = new MyHandler(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		FinalActivity.initInjectedView(this); //置于setContentView之后,否则会空指针

		mPtrScrollView = (PullToRefreshScrollView) findViewById(R.id.main_scroll);
		mScrollViewRefreshProxy = new ScrollViewRefreshProxy(mPtrScrollView);
		mScrollViewRefreshProxy.setOnRefreshActionListener(this);

		mTimeLimitImg1.setVisibility(View.GONE);
		mTimeLimitImg2.setVisibility(View.GONE);
		mTimeLimitImg3.setVisibility(View.GONE);


		//将猜你喜欢改成下拉形式 ------------------------------------
		mProductRecommendAdapter = new MainProductRecommendAdapter(this, R.layout.item_main_product_recommend);
		mProductRecommendGrid.setAdapter(mProductRecommendAdapter);

		mProductRecommendGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> paramAdapterView,
					View view, int position, long id) {
				Intent intent = new Intent(MainActivity.this,ProductDetailActivity.class);
				intent.putExtra("productID", mProductRecommendAdapter.getData().get(position).getId()+"");
				startActivity(intent);
			}

		});

		mScrollViewRefreshProxy.refreshing();
	}

	private void InitData() {
		if (!NetworkUtil.isNetworkConnected(this)) {							// 判断是否联网

			App.showShortToast("当前未检测到网络链接");
			mScrollViewRefreshProxy.loadRefreshActionComplete();
			return;
		}

		/** 获取广告 */
		getAdvertisementsAsync(); 
		/** 获取特卖 */
		getSpecialSaleSync();  
		/** 获取9个品牌推荐 */
		getBrandRecommendAsync();
		/** 猜你喜欢 */
		getRecommendAsync();  
		/** 品牌团购推荐 */
		getGrouponsRecommendAysnc();
	}

	//Load Data Async .................................................

	/** 获取品牌团购推荐 */
	private void getGrouponsRecommendAysnc() {
		new Thread(){
			public void run() {
				try {
					mGroupRecommend = WebClient.getInstance(MainActivity.this).getGrouponsRecommend(3);
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode())){
						mGroupRecommend = null;
					}else {
						e.printStackTrace();
						App.showLog("Get Recommand fail=="+e.toString());
					}
				}catch (Exception e) {
				}
				mHandler.sendEmptyMessage(5);
			};
		}.start();

	}


	/** 获取猜你喜欢 */
	private void getRecommendAsync() {
		new Thread(){
			public void run() {
				try {
					PageEntity<Product> entry = WebClient.getInstance(MainActivity.this).getRecommend();

					mRecommend = entry.getContent();

					mHandler.sendEmptyMessage(4);
				} catch (WebException e) {
					App.showLog("Get Recommand fail=="+e.toString());
				}catch (Exception e) {
					App.showLog("Get Recommand fail=="+e.toString());
					App.showShortToast("未知错误");					
				}
			};
		}.start();


	}


	private void getAdvertisementsAsync() {
		new Thread(){
			public void run() {
				try {
					//获取首页头部广告
					mTopAdvertisement = WebClient.getInstance(MainActivity.this).adVertisement("APP首页", "TOP_LB");
					mAdServings = mTopAdvertisement.getActiveServings();
					mHandler.sendEmptyMessage(0);
				} catch (Exception e) {
					mAdServings = new ArrayList<MainTopAdvertisement.AdServing>();
					mHandler.sendEmptyMessage(0);
					Log.w(TAG, "Get advertisement fail," + e.toString());
				}
			};
		}.start();
	}

	/** 获取特卖 */
	private void getSpecialSaleSync() {
		new Thread(){
			public void run() {
				try {
					msEntity = WebClient.getInstance(MainActivity.this).active("active", 1, 3, "endTime", "asc");
					mSpecialSales = msEntity.getContent();

				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode())){
						mSpecialSales = null;
					}

				}catch (Exception e) {
					App.showLog("Get special sale," + e.toString());
				} 
				mHandler.sendEmptyMessage(1);
			};
		}.start();
	}
	/**获取9个品牌 */
	private void getBrandRecommendAsync() {
		new Thread(){
			public void run() {
				try {
					mBrandRecommends = WebClient.getInstance(MainActivity.this).getBrand();
					mHandler.sendEmptyMessage(3);
				} catch (WebException e) {
					Log.w(TAG, "Get Brand Recommend fail," + e.toString());
				}catch (Exception e) {
					Log.w(TAG, "Get Brand Recommend fail," + e.toString());
				}
			};
		}.start();
	}


	//UI Events .....................................

	/**
	 * 点击事件
	 */
	public void butClick(View v){
		//摇一摇
		if( v == mRightImg ){
			ToShakeActivity();
		}
		//搜索
		if( v == mSearchEdit ){
			ToSearchActivity();
		}
		//私人定制
		if( v == mAttentionLin ){
			//			ContextUtil.startActivity(this, FollowActivity.class);			
			ContextUtil.startActivity(this, PrivateCustomActivity.class);			
		}
		//360全景
		if( v == mPanoramaLin ){
			ContextUtil.startActivity(this, PanoramicActivity.class);			
		}
		//品牌团购
		if( v == mGroupLin ){
			ContextUtil.startActivity(this, GroupActivity.class);
		}
		//品牌推荐
		if( v == mRecommendLin ){
			ContextUtil.startActivity(this, BrandRecommendActivity.class);
		}
		//特卖
		if( v == mTimeLimitLin){
			ContextUtil.startActivity(this, TimeLimitedSaleActivity.class);
		}
		//团购
		if(v == mBrandGroupLin){
			ContextUtil.startActivity(this, GroupActivity.class);
		}

	}
	private void ToSearchActivity(){ 
		ContextUtil.startActivity(this, SearchActivity.class);		
	}


	private void ToShakeActivity() {
		ContextUtil.startActivity(this, ShakeAvtivity.class);
	}

	private  class MyHandler extends Handler{

		private final WeakReference<Activity> mActivity; // activity弱引用

		public MyHandler(Activity activity) {  
			mActivity = new WeakReference<Activity>(activity);  
		}  

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if( mActivity.get() != null ){ //activity若已销毁。不做任何处理
				switch (msg.what) {
				case 0:
					initBranner();
					
					mScrollViewRefreshProxy.loadRefreshActionComplete();
					break;

				case 1:
					setTimeLimitDate();				
					mScrollViewRefreshProxy.loadRefreshActionComplete();
					break;

				case 3:

					initViewpage();
					mScrollViewRefreshProxy.loadRefreshActionComplete();
					break;
				case 4:
					//猜你喜欢

					mProductRecommendAdapter.update(mRecommend);
					mScrollViewRefreshProxy.loadRefreshActionComplete();
					break;
				case 5:
					//品牌团购推荐
					if(mGroupRecommend == null || mGroupRecommend.isEmpty()){
						mBrandGroupLin.setVisibility(View.GONE);
					}else{

						ImageView[] groupImgs = new ImageView[3];
						groupImgs[0] = mGroupImg1;
						groupImgs[1] = mGroupImg2;
						groupImgs[2] = mGroupImg3;

						for (int i = 0; i < mGroupRecommend.size(); i++) {
							ImageLoader.getInstance().displayImage(mGroupRecommend.get(i).getImage(), groupImgs[i]);
						}	
						mBrandGroupLin.setVisibility(View.VISIBLE);
					}
					mScrollViewRefreshProxy.loadRefreshActionComplete();
					break;

				default:
					break;
				}
			}
		}
		
	}
	
	/** 初始化顶部branner滚动视图 */
	private void initBranner() {
		//判空。。
		if(mAdServings == null || mAdServings.size() == 0 ){
			mMainPageLin.setVisibility(View.GONE);
			return;
		}

		String[] urlImageList  = new String[mAdServings.size()];
		for (int i = 0; i < mAdServings.size(); i++) {
			urlImageList[i] = mAdServings.get(i).getAdMaterial().getPath();
		}	     

		mMainPageGalleryView.start(getApplicationContext(), urlImageList, 3000,
				mMainPageGalleryLin, R.drawable.dot_focused, R.drawable.dot_normal);

		mMainPageGalleryView.setMyOnItemClickListener(new MyOnItemClickListener() {
			public void onItemClick(int curIndex) {
				App.showLog("下标=="+curIndex);
			}
		});
		
	}

	/** 初始化viewpage  */
	private void initViewpage() {
		if( mBrandRecommends == null || mBrandRecommends.size() == 0  ){
			mMainViewpageLin.setVisibility(View.GONE);
			return;
		}
		
		mMainViewpageLin.setVisibility(View.VISIBLE);

		//防止刷新的时候点错位
		curIndex = 0;
		oldIndex = 0;

		mViewPage.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				App.showLog("item_selete"+position);
				curIndex = position % viewList.size();
				App.showLog("curIndex=="+curIndex);
				App.showLog("oldIndex=="+oldIndex);
				if (mOvalLayout != null && viewList.size() > 1) { // 切换圆点

					mOvalLayout.getChildAt(oldIndex).setBackgroundResource(R.drawable.dot_normal); // 圆点取消
					mOvalLayout.getChildAt(curIndex).setBackgroundResource(R.drawable.dot_focused);// 圆点选中
					oldIndex = curIndex;
				}
			}

			@Override
			public void onPageScrolled(int paramInt1, float paramFloat, int paramInt2) {

			}
			@Override
			public void onPageScrollStateChanged(int paramInt) {
			}
		});


		viewList = new ArrayList<View>();// 将要分页显示的View装入数组中
		LayoutInflater inflater = getLayoutInflater();
		for (int i = 0; i < 3; i++) {
			final int j = i;

			view = inflater.inflate(R.layout.item_main_brand_viewpage, null);
			ImageView imageView1 = (ImageView) view.findViewById(R.id.item_viewpage_image1);
			ImageView imageView2 = (ImageView) view.findViewById(R.id.item_viewpage_image2);
			ImageView imageView3 = (ImageView) view.findViewById(R.id.item_viewpage_image3);
			TextView textView1 = (TextView) view.findViewById(R.id.item_viewpage_text1);
			TextView textView2 = (TextView) view.findViewById(R.id.item_viewpage_text2);
			TextView textView3 = (TextView) view.findViewById(R.id.item_viewpage_text3);

			ImageLoader.getInstance().displayImage(mBrandRecommends.get(j*3).getAppImage(), imageView1);
			ImageLoader.getInstance().displayImage(mBrandRecommends.get(j*3+1).getAppImage(), imageView2);
			ImageLoader.getInstance().displayImage(mBrandRecommends.get(j*3+2).getAppImage(), imageView3);
			textView1.setText(mBrandRecommends.get(j*3).getName());
			textView2.setText(mBrandRecommends.get(j*3+1).getName());
			textView3.setText(mBrandRecommends.get(j*3+2).getName());

			imageView1.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Log.d("TAG", "viewview-imageView1_onclick");

					Intent intent = new Intent(MainActivity.this,BrandListActivity.class);
					intent.putExtra("brandId", mBrandRecommends.get(j*3).getId()+"");
					intent.putExtra("brandName", mBrandRecommends.get(j*3).getName());
					startActivity(intent);

				}
			});

			imageView2.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Log.d("TAG", "view-imageView2-onclick");

					Intent intent = new Intent(MainActivity.this,BrandListActivity.class);
					intent.putExtra("brandId", mBrandRecommends.get(j*3+1).getId()+"");
					intent.putExtra("brandName", mBrandRecommends.get(j*3+1).getName());
					startActivity(intent);
				}
			});
			imageView3.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Log.d("TAG", "view-imageView3-onclick");

					Intent intent = new Intent(MainActivity.this,BrandListActivity.class);
					intent.putExtra("brandId", mBrandRecommends.get(j*3+2).getId()+"");
					intent.putExtra("brandName", mBrandRecommends.get(j*3+2).getName());
					startActivity(intent);
				}
			});
			viewList.add(view);			
		}

		initOvalLayout();

		mViewPage.setAdapter(pagerAdapter);
	}



	//添加数据
	private void setTimeLimitDate() {

		if(mSpecialSales == null || mSpecialSales.isEmpty()){
			mTimeLimitLin.setVisibility(View.GONE); 
			return;
		}

		mTimeLimitImg1.setVisibility(View.VISIBLE);
		mTimeLimitImg2.setVisibility(View.VISIBLE);
		mTimeLimitImg3.setVisibility(View.VISIBLE);

		ImageView[] img = new ImageView[3];
		img[0] = mTimeLimitImg1;
		img[1] = mTimeLimitImg2;
		img[2] = mTimeLimitImg3;


		//为了应付有时候后台给的特卖不足三个
		if(img.length > mSpecialSales.size() ){
			for (int i = 0; i < mSpecialSales.size(); i++) {
				ImageLoader.getInstance().displayImage(mSpecialSales.get(i).getImage(), img[i]);
			}
		}else {
			for (int i = 0; i < img.length; i++) {
				ImageLoader.getInstance().displayImage(mSpecialSales.get(i).getImage(), img[i]);
			}
		}
		//时间差，结束时间与当前时间
		long date = (msEntity.getContent().get(0).getEndTime()-msEntity.getNowDate());

		//		CustomDigitalClock remainTime = (CustomDigitalClock) findViewById(R.id.time_limit_time_text);
		CountdownClock remainTime = (CountdownClock) findViewById(R.id.time_limit_time_text);
		remainTime.setEndTime(System.currentTimeMillis()+date);
		remainTime.setClockListener(new ClockListener() {

			@Override
			public void timeEnd() {
				getSpecialSaleSync();
			}

			@Override
			public void remainFiveMinutes() {
				Log.d(TAG, "remain five minutes....");
			}
		});

	}


	//UI Data Adapter Implements -----------------------------------------------

	public class MainGridGuessYouLikeAdapter extends AbsViewHolderAdapter<Product>{

		public MainGridGuessYouLikeAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Product itemData) {
			ImageView Image = getViewFromHolder(R.id.item_grid_image);
			TextView mNameText = getViewFromHolder(R.id.recommend_product_name);
			TextView mPriceText = getViewFromHolder(R.id.recommend_product_price);


			ImageLoader.getInstance().displayImage(itemData.getImage(), Image);
			mNameText.setText(itemData.getName());
			mPriceText.setText("￥"+itemData.getPrice());

			mNameText.setVisibility(View.GONE);
			mPriceText.setVisibility(View.GONE);
		}	

	}


	@Override
	public void onRefresh() {
		InitData();
	}

	/** 单品推荐 adapter */
	public class MainProductRecommendAdapter extends AbsViewHolderAdapter<Product>{

		public MainProductRecommendAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Product itemData) {
			ImageView mImage = getViewFromHolder(R.id.item_main_product_recommend_image);
			TextView mText = getViewFromHolder(R.id.item_main_product_recommend_name_txt);
			TextView mText1 = getViewFromHolder(R.id.item_item_main_product_recommend_price_txt);

			ImageLoader.getInstance().displayImage(itemData.getImage(), mImage);
			mText.setText(itemData.getName());
			mText1.setText("￥"+itemData.getPrice()+"");
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}

	private boolean isFirst = true;
	@Override
	protected void onResume() {
		//		dInitData();
		super.onResume();

		//		if(isFirst){
		//			isFirst = false;
		//		}else {
		//			dInitData();
		//		}
	}

	  PagerAdapter pagerAdapter = new PagerAdapter() {

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			//根据传来的key，找到view,判断与传来的参数View arg0是不是同一个视图

			return arg0 == viewList.get((int)Integer.parseInt(arg1.toString()));
		}

		@Override
		public int getCount() {
			return viewList.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position,
				Object object) {
			container.removeView(viewList.get(position));
		}
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(viewList.get(position));
			//把当前新增视图的位置（position）作为Key传过去
			return position;
		}
	};


	/** 初始化圆点 */
	private void initOvalLayout() {

		if (mOvalLayout != null && viewList.size() < 2) {// 如果只有一第图时不显示圆点容器
			mOvalLayout.removeAllViews();
			mOvalLayout.getLayoutParams().height = 0;
		} else if (mOvalLayout != null) {
			mOvalLayout.removeAllViews();
			// 圆点的大小是 圆点窗口的 70%;
			int Ovalheight = (int) (mOvalLayout.getLayoutParams().height * 0.7);
			// 圆点的左右外边距是 圆点窗口的 20%;
			int Ovalmargin = (int) (mOvalLayout.getLayoutParams().height * 0.2);
			android.widget.LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					Ovalheight, Ovalheight);
			layoutParams.setMargins(Ovalmargin, 0, Ovalmargin, 0);
			for (int i = 0; i < viewList.size(); i++) {
				View v = new View(MainActivity.this); // 圆点
				v.setLayoutParams(layoutParams);
				v.setBackgroundResource(R.drawable.dot_normal);
				mOvalLayout.addView(v);
			}
			// 选中第一个
			mOvalLayout.getChildAt(0).setBackgroundResource(R.drawable.dot_focused);
		}
	}

	@Override
	protected void onStop() {
		mMainPageGalleryView.stopTimer();
		super.onStop();
	}
	@Override
	protected void onRestart() {
//		InitData();
		mMainPageGalleryView.startTimer();
		super.onRestart();
	}


}
